import { ref, reactive, toRefs, onMounted, nextTick, onActivated } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'

const tabDTO: any = {
  task: [
    { title: '未派发', name: '1' },
    { title: '验收中', name: '2' },
    { title: '已提交', name: '3' },
    { title: '已完成', name: '4' }
  ],
  soft: [
    { title: '验收中', name: '2' },
    { title: '未派发', name: '1' },
    { title: '已完成', name: '3' }
  ],
  hard: [
    { title: '验收中', name: '2' },
    { title: '未派发', name: '1' },
    { title: '已完成', name: '3' }
  ]
}

/**
 * Tab分页
 * @param {string} pageSource 所属页面（ task 任务管理，soft 软装，hard 硬装）
 */
export function TabPage(pageSource: string, $router: any, $store: any, instance: any) {
  const datas = reactive({
    searchValue: '',
    activeTab: '1',
    tabs: tabDTO[pageSource],
    listReLoad: false, // 是否需要重新加载列表
    showReview: false,
    activeRowData: {}
  })

  const listRefs: {
    [key: string]: any
  } = {}
  const setListRef = (el: any, name: string) => {
    if (el) {
      listRefs[name] = el
    }
  }
  const onSearch = () => {
    // 搜索
    tabOnChange()
  }
  const onClear = () => {
    // 搜索
    tabOnChange()
  }

  // 复查确认
  const onReview = (row: any) => {
    datas.activeRowData = row
    nextTick(() => {
      datas.showReview = true
    })
  }

  const onCreate = () => {
    const query: { [key: string]: any } = {
      source: pageSource
    }
    $router.push({
      path: `/task/create`,
      query
    })
  }
  const tabOnChange = () => {
    nextTick(() => {
      listRefs[`${datas.activeTab}`] && listRefs[`${datas.activeTab}`].resetPageData()
    })
  }
  onMounted(() => {})
  onBeforeRouteLeave((to, from, next) => {
    const instanceName = instance?.type?.name
    if (to.name === 'Index') {
      $store.commit('routerKeep/removeCache', instanceName)
    } else {
      $store.commit('routerKeep/resetCache', instanceName)
    }
    next()
  })

  const { proxy }: any = instance
  proxy.$SimpleEvents.registerEvent('refreshTaskList', () => {
    listRefs[`${datas.activeTab}`] && listRefs[`${datas.activeTab}`].resetPageData()
    datas.listReLoad = true
  })
  proxy.$SimpleEvents.registerEvent('refreshTaskItem', (id: any) => {
    if (!id) return
    listRefs[`${datas.activeTab}`] && listRefs[`${datas.activeTab}`].refreshItem(id)
  })
  // 监听操作tab切换
  proxy.$SimpleEvents.registerEvent('changeTaskListTab', (name: any) => {
    if (!name) return
    const flag = datas.tabs.some((v: any) => v.name === name)
    if (flag) {
      datas.activeTab = name
    }
    datas.listReLoad = true
  })

  onActivated(() => {
    // 缓存路由才生效
    if (datas.listReLoad) {
      listRefs[`${datas.activeTab}`] && listRefs[`${datas.activeTab}`].resetPageData()
    }
    datas.listReLoad = false
  })

  return {
    datas,
    onSearch,
    onClear,
    onCreate,
    tabOnChange,
    setListRef,
    onReview
  }
}
